/**
 * zsw zswemail@qq.com
 */
;$(document).ready(function() {
    "use strict";

    /**
     * 菜单选中
     * @param page 菜单
     */
    function selMenu(page) {
        let _p = $('a.z_frame[href="' + page + '"]')
        $('.active-page').removeClass('active-page')
        _p.parent().addClass('active-page')
        let parentNode = _p.parent().parent()
        let mainId
        if (parentNode.hasClass('sub-menu')) {
            if (!parentNode.parent().hasClass('open')) {
                parentNode.prev().click()
            }
            mainId = parentNode.parent().parent().attr('id')
        } else if (parentNode.hasClass('accordion-menu')) {
            parentNode.click()
            mainId = parentNode.attr('id')
        }
        if (mainId) {
            $('.target-secondary-sidebar[data-target="' + mainId + '"]').trigger('click')
        }
    }

    // -------------顶部页面tab---------------------

    let TabMenu = function(){
        if (!(this instanceof TabMenu)) return new TabMenu();

        this.autoPk = 1
        this.current = ''
        this.tabs = []
        $(window).resize( () => {this.size()})
    }

    TabMenu.prototype = {
        construct: TabMenu,
        append(url, title, def){
            let l = this.tabs.length
            for (let i = 0;i < l;i++) {
                if (this.tabs[i].url === url) {
                    this.toggle(this.tabs[i].pk)
                    return
                }
            }

            let pk = this.autoPk

            this.tabs.push({pk, url, title, fixed: false})
            this.appendTab(pk, title, !!def)
            this.appendFrame(pk, url)
            this.setCurrent(pk)
            this.autoPk++
        },
        setCurrent(pk) {
            this.current = pk
        },
        tabScrollCur(){
            this.size()
            $('.page-tabs').animate({
                scrollLeft: $('.page-tabs > li.cur')[0].offsetLeft - 20
            }, 200);
        },
        appendTab(pk, title, def = false){
            $('.page-tabs > .cur').removeClass('cur')
            let li = document.createElement('li')
            $(li).attr('data-frame_id', pk)
            $(li).addClass('cur ' + (def ? 'def' : ''))
            $(li).html('<i class="refresh-tab ri-refresh-line" style="display: none;"></i><a href="javascript:void(0)">'+ title +'</a><i class="close-tab ri-close-line" style="display: none;"></i>')
            $('.page-tabs').append(li)
            this.tabScrollCur()
        },
        appendFrame(pk, url)
        {
            $('.contentBox.cur').removeClass('cur')
            let box = document.createElement('div')
            $(box).addClass('contentBox cur')
            $(box).attr('id', 'frame' + pk)
            $(box).html("<iframe width='100%' src='"+url+"' frameborder='0' seamless>")
            $('#content-main').append(box)
        },
        toggle(pk){
            $('.contentBox.cur').removeClass('cur')
            $('.page-tabs > li').removeClass('cur')
            $('.page-tabs > li[data-frame_id="' + pk + '"]').addClass('cur')
            $('#frame' + pk).addClass('cur')
            this.setCurrent(pk)
            this.tabScrollCur()
        },
        refresh(pk){
            $('#frame' + pk + ' > iframe').attr('src', $('#frame' + pk + ' > iframe').attr('src'));
        },
        remove(pk){
            let s = false,l = this.tabs.length,i = 0

            for (;i < l;i++) {
                if (this.tabs[i].pk === pk) {
                    this.tabs.splice(i, 1)
                    s = true
                    break
                }
            }
            if (s) {
                this.removeTab(pk)
                this.removeFrame(pk)
            }

            let next
            if (this.tabs.length > 0) {
                next = this.tabs[i] || this.tabs[this.tabs.length - 1]
                this.toggle(next.pk)
            }
        },
        removeTab(pk){
            $('.page-tabs > li[data-frame_id="' + pk + '"]').remove()
        },
        removeFrame(pk){
            $('#frame' + pk).remove()
        },
        size(){
            // 计算滚动条
            let l = this.tabs.length,i = 0,use = 0
            for (;i < l;i++) {
                use += (this.tabs[i].title.replace(/<.*?>/ig, '').length * 12) + 40 + 1  // 字体长度 + padding + 空格误差
            }
            if (use > $('.navbar-collapse').width()) {
                $('.navbar-expand-md .navbar-nav.page-tabs').css('flex-direction', 'column')
            }else{
                $('.navbar-expand-md .navbar-nav.page-tabs').css('flex-direction', 'row')
            }
        },
        detail(pk){
            let l = this.tabs.length
            for (let i = 0;i < l;i++) {
                if (this.tabs[i].pk === pk) {
                    return this.tabs[i];
                }
            }
        }
    }

    let tabs = new TabMenu()

    // 注册默认页面
    // tabs.append('index/home', '<i class="ri-airplay-fill"></i> 控制台', true)

    $('.page-tabs').on('mouseenter', '>li:not(.def)', function(){
        $(this).find('.close-tab').show();
        $(this).find('.refresh-tab').show();
    })
    $('.page-tabs').on('mouseleave', '>li:not(.def)', function(){
        $(this).find('.close-tab').hide();
        $(this).find('.refresh-tab').hide();
    })
    $('.page-tabs').on('click', '.close-tab', function (event) {
        event.stopPropagation();
        tabs.remove($(this).parent('li').data('frame_id'))
    })
    $('.page-tabs').on('click', '.refresh-tab', function (event) {
        event.stopPropagation();
        tabs.refresh($(this).parent('li').data('frame_id'))
    })
    $('.page-tabs').on('click', '>li[data-frame_id]:not(.cur)', function () {
        $('.page-tabs>li').removeClass('cur')
        $(this).addClass('cur')
        tabs.toggle($(this).data('frame_id'))

        selMenu(tabs.detail($(this).data('frame_id')).url)
    })
    // -------------顶部页面tab end ---------------------

    // ------------- 移动端菜单开关 ---------------------
    $("#sidebar-toggle-button").on("click", function () {
        $('.page-container').addClass('sidebar-modal')
    })
    $(".shield").on('click', function () {
        $('.sidebar-modal').removeClass('sidebar-modal')
    })
    // -------------移动端菜单开关 end ---------------------

    $('a.z_frame').on('click', function (event) {
        event = event || window.event;
        if(event.preventDefault){
            event.preventDefault();
        }else{
            event.returnValue = false;
        }

        $('li.active-page').removeClass('active-page')
        $(this).parent().addClass('active-page')
        let title = $(this).find('i.menu-icon')
        title = title.length === 0 ? $(this).find('.menu-img') : title
        title = title.length === 0 ? '' : title.get(0).outerHTML
        tabs.append($(this).attr('href'),  title + ' ' + $(this).text().replace(/(^\s*)|(\s*$)/g, ""));
    })

    $('.target-secondary-sidebar').on('click', function () {
        $('.target-secondary-sidebar.cur').removeClass('cur')
        $(this).addClass('cur')
        $('.accordion-menu[id^="accordion-menu-"]').hide()
        let target = $("#" + $(this).data('target')),
            title = $(this).data('original-title')
        target && target.show()
        $('.logo-box span').text(title);
    })

    $('.secondary-sidebar-menu').on('click', 'a.z_frame', function () {
        sessionStorage.setItem("defaultPage", $(this).attr('href'));
    })

    let theme_prefix = 'theme-'
    let theme_name = sessionStorage.getItem("default-theme")
    $('.theme-box').on('click', '.theme-list', function () {
        $('body').removeClass(theme_prefix + theme_name)
        theme_name = $(this).data('name')
        $('body').addClass(theme_prefix + theme_name)
        $('.theme-box .theme-list').removeClass('cur')
        $('.theme-box .theme-list[data-name="'+theme_name+'"]').addClass('cur')
        sessionStorage.setItem("default-theme", theme_name);
    })

    ;(function() {
        // >>>> 默认菜单选中 >>>>
        let defaultPage = sessionStorage.getItem("defaultPage");
        if (!defaultPage || $('.secondary-sidebar-menu').find('a.z_frame[href="'+defaultPage+'"]').length === 0) {
            let firstA = $('.secondary-sidebar-menu ul.accordion-menu:eq(0) li:eq(0) .z_frame:eq(0)')
            defaultPage = firstA.attr('href')
        }

        $('a.z_frame[href="' + defaultPage + '"]').click()
        selMenu(defaultPage)
        // <<<< 默认菜单选中 <<<<

        // 主题
        if (!theme_name || $('.theme-box').find('.theme-list[data-name="'+theme_name+'"]').length < 1) { theme_name = 'black' }
        $('.theme-box').find('.theme-list[data-name="'+theme_name+'"]').click()
    }())
});
